<template>
  <div class="home-page">
    <!-- 顶部导航 -->
    <van-nav-bar 
      :title="pageTitle"
      class="top-nav"
    >
      <template #left>
        <div class="nav-user" @click="showUserMenu = true">
          <div class="user-avatar">
            <van-icon name="user-o" />
          </div>
        </div>
      </template>
      <template #right>
        <van-icon 
          name="replay" 
          size="22" 
          @click="handleRefresh"
          :class="{ 'rotating': refreshing }"
        />
      </template>
    </van-nav-bar>
    
    <!-- 主内容区 -->
    <div class="main-content">
      <van-pull-refresh v-model="refreshing" @refresh="handleRefresh">
        <router-view v-slot="{ Component }">
          <keep-alive>
            <component :is="Component" />
          </keep-alive>
        </router-view>
      </van-pull-refresh>
    </div>
    
    <!-- 底部导航 -->
    <van-tabbar v-model="activeTab" route class="bottom-nav">
      <van-tabbar-item to="/home/calendar" icon="calendar-o" name="calendar">
        日历
      </van-tabbar-item>
      <van-tabbar-item to="/home/records" icon="orders-o" name="records">
        记录
      </van-tabbar-item>
      <van-tabbar-item to="/home/statistics" icon="chart-trending-o" name="statistics">
        统计
      </van-tabbar-item>
    </van-tabbar>
    
    <!-- 用户菜单 -->
    <van-action-sheet
      v-model:show="showUserMenu"
      :actions="userMenuActions"
      cancel-text="取消"
      @select="handleUserMenuSelect"
      class="user-menu-sheet"
    >
      <template #description>
        <div class="user-info">
          <div class="user-avatar-large">
            <van-icon name="user-o" size="32" />
          </div>
          <div class="user-details">
            <div class="user-greeting">欢迎使用</div>
            <div class="trip-status" v-if="store.user.tripStartDate">
              <van-icon name="location-o" size="14" />
              <span>出差开始: {{ store.user.tripStartDate }}</span>
            </div>
            <div class="trip-status no-trip" v-else>
              <van-icon name="warning-o" size="14" />
              <span>尚未设置出差开始日期</span>
            </div>
          </div>
        </div>
      </template>
    </van-action-sheet>
    
    <!-- 设置出差日期弹窗 -->
    <van-popup
      v-model:show="showTripDatePicker"
      position="bottom"
      round
      class="date-picker-popup"
    >
      <van-date-picker
        v-model="tripDateValue"
        title="选择出差开始日期"
        :min-date="minTripDate"
        :max-date="maxTripDate"
        @confirm="handleTripDateConfirm"
        @cancel="showTripDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog, showConfirmDialog } from 'vant'
import { useAppStore } from '../stores/index.js'

const router = useRouter()
const route = useRoute()
const store = useAppStore()

const activeTab = ref('calendar')
const showUserMenu = ref(false)
const showTripDatePicker = ref(false)
const refreshing = ref(false)

// 出差日期选择器
const tripDateValue = ref([
  new Date().getFullYear().toString(),
  (new Date().getMonth() + 1).toString().padStart(2, '0'),
  new Date().getDate().toString().padStart(2, '0')
])
const minTripDate = new Date(2020, 0, 1)
const maxTripDate = new Date()

const pageTitle = computed(() => {
  const titles = {
    'calendar': '日历',
    'records': '休息记录',
    'statistics': '统计概览'
  }
  return titles[activeTab.value] || '工作时间记录'
})

const userMenuActions = computed(() => {
  const actions = []
  
  if (!store.user.tripStartDate) {
    actions.push({ 
      name: '设置出差开始日期', 
      value: 'setTripDate',
      color: '#6366f1'
    })
  } else {
    actions.push({ 
      name: '修改出差开始日期', 
      value: 'setTripDate',
      color: '#f59e0b'
    })
  }
  
  actions.push({ 
    name: '退出登录', 
    value: 'logout',
    color: '#ef4444'
  })
  
  return actions
})

const handleUserMenuSelect = async (action) => {
  showUserMenu.value = false
  
  if (action.value === 'setTripDate') {
    // 如果已有出差日期，设置为当前值
    if (store.user.tripStartDate) {
      const parts = store.user.tripStartDate.split('-')
      tripDateValue.value = parts
    }
    showTripDatePicker.value = true
  } else if (action.value === 'logout') {
    try {
      await showConfirmDialog({
        title: '确认退出',
        message: '确定要退出登录吗？'
      })
      
      await store.logout()
      showToast({
        message: '已退出登录',
        icon: 'success'
      })
      router.push('/login')
    } catch (e) {
      // 用户取消
    }
  }
}

const handleTripDateConfirm = async ({ selectedValues }) => {
  const dateStr = selectedValues.join('-')
  
  try {
    // 如果已有出差日期，需要确认
    if (store.user.tripStartDate) {
      await showConfirmDialog({
        title: '修改出差开始日期',
        message: `确定将出差开始日期修改为 ${dateStr} 吗？`
      })
    }
    
    await store.setTripStartDate(dateStr)
    showTripDatePicker.value = false
    showToast({
      message: '设置成功',
      icon: 'success'
    })
    
    // 刷新统计数据
    if (store.user.tripStartDate) {
      await store.getStatistics({ includeTravel: store.includeTravel })
    }
  } catch (error) {
    if (error !== 'cancel' && error.message !== 'cancel') {
      showToast({
        message: error.message || '设置失败',
        icon: 'fail'
      })
    }
  }
}

const handleRefresh = async () => {
  refreshing.value = true
  
  try {
    await Promise.all([
      store.getUserStatus(),
      store.getHolidayData(store.currentYear)
    ])
    
    if (store.user.tripStartDate) {
      await store.getStatistics({ includeTravel: store.includeTravel })
    }
    
    showToast({
      message: '刷新成功',
      icon: 'success',
      duration: 1000
    })
  } catch (error) {
    showToast({
      message: '刷新失败',
      icon: 'fail'
    })
  } finally {
    refreshing.value = false
  }
}

// 监听路由变化更新activeTab
watch(() => route.path, (path) => {
  if (path.includes('calendar')) activeTab.value = 'calendar'
  else if (path.includes('records')) activeTab.value = 'records'
  else if (path.includes('statistics')) activeTab.value = 'statistics'
}, { immediate: true })

onMounted(async () => {
  // 检查登录状态
  if (!store.checkLoginStatus()) {
    showToast('请先登录')
    router.push('/login')
    return
  }
  
  // 验证token
  const isValid = await store.validateToken()
  if (!isValid) {
    showToast({
      message: '登录已过期',
      icon: 'fail'
    })
    await store.logout()
    router.push('/login')
    return
  }
  
  // 加载数据
  try {
    await Promise.all([
      store.getUserStatus(),
      store.getHolidayData(store.currentYear)
    ])
    
    if (store.user.tripStartDate) {
      await store.getStatistics({ includeTravel: store.includeTravel })
    }
  } catch (error) {
    console.error('数据加载失败:', error)
  }
})
</script>

<style scoped>
.home-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--app-bg);
}

/* 顶部导航 */
.top-nav {
  background: var(--card-bg) !important;
  border-bottom: 1px solid var(--border-color);
  flex-shrink: 0;
}

.top-nav :deep(.van-nav-bar__title) {
  color: var(--text-primary);
  font-weight: 600;
  font-size: 17px;
}

.top-nav :deep(.van-icon) {
  color: var(--text-primary);
}

.nav-user {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  width: 32px;
  height: 32px;
  background: var(--accent-gradient);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar :deep(.van-icon) {
  color: white;
  font-size: 18px;
}

.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 主内容区 */
.main-content {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px; /* 底部导航高度 */
}

/* 底部导航 */
.bottom-nav {
  background: var(--card-bg) !important;
  border-top: 1px solid var(--border-color);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.bottom-nav :deep(.van-tabbar-item) {
  color: var(--text-muted);
}

.bottom-nav :deep(.van-tabbar-item--active) {
  color: var(--accent-primary);
}

.bottom-nav :deep(.van-tabbar-item__icon) {
  font-size: 22px;
  margin-bottom: 4px;
}

.bottom-nav :deep(.van-tabbar-item__text) {
  font-size: 11px;
}

/* 用户菜单 */
.user-menu-sheet :deep(.van-action-sheet__description) {
  padding: 20px;
  background: var(--card-bg);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar-large {
  width: 56px;
  height: 56px;
  background: var(--accent-gradient);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.user-avatar-large :deep(.van-icon) {
  color: white;
}

.user-details {
  flex: 1;
}

.user-greeting {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 6px;
}

.trip-status {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: var(--success-color);
}

.trip-status.no-trip {
  color: var(--warning-color);
}

/* 日期选择器弹窗 */
.date-picker-popup {
  background: var(--card-bg) !important;
}

.date-picker-popup :deep(.van-picker) {
  background: var(--card-bg) !important;
}

.date-picker-popup :deep(.van-picker__toolbar) {
  background: var(--card-bg);
}

.date-picker-popup :deep(.van-picker__title) {
  color: var(--text-primary);
}

.date-picker-popup :deep(.van-picker__confirm) {
  color: var(--accent-primary);
}

.date-picker-popup :deep(.van-picker__cancel) {
  color: var(--text-muted);
}

.date-picker-popup :deep(.van-picker-column__item) {
  color: var(--text-secondary);
}

.date-picker-popup :deep(.van-picker-column__item--selected) {
  color: var(--text-primary);
}

.date-picker-popup :deep(.van-picker__mask) {
  background: linear-gradient(180deg, 
    rgba(255, 255, 255, 0.9) 0%, 
    rgba(255, 255, 255, 0.4) 50%, 
    rgba(255, 255, 255, 0.9) 100%
  );
}

.date-picker-popup :deep(.van-picker__frame) {
  border-color: var(--border-color);
}
</style>

